package com.wondersgroup.hs.mobile.report.support.dataSource;

import com.fr.base.FRContext;
import com.fr.base.Parameter;
import com.fr.data.AbstractTableData;
import com.fr.general.data.TableDataException;
import com.fr.stable.ParameterProvider;
import com.wondersgroup.hs.mobile.his.api.dto.QueryHisPatientReq;
import com.wondersgroup.hs.mobile.his.api.model.HisPatient;
import com.wondersgroup.hs.mobile.his.api.service.HisADTService;
import com.wondersgroup.hs.mobile.nursing.rpc.utils.ClientServiceFactory;
import com.wondersgroup.hs.mobile.report.support.ReflectUtils;

import java.beans.PropertyDescriptor;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;

/**
 * Created by zarra on 2016/12/27.
 */
public class HisPatientDS extends AbstractTableData {

    List<HisPatient> hisPatients = null;
    HisADTService hisADTService;
    PropertyDescriptor[] propertyDescriptors;

    public HisPatientDS() throws MalformedURLException {

        propertyDescriptors = ReflectUtils.getPropertyDescriptors(HisPatient.class);
        hisADTService = ClientServiceFactory.service(HisADTService.class,new URL("http://192.168.6.109:8080/his/public/rpc"));
        setDefaultParameters(new Parameter[] { new Parameter("patientID") });

    }


    @Override
    public int getColumnCount() throws TableDataException {
        //init();
        return propertyDescriptors.length;
    }

    @Override
    public String getColumnName(int i) throws TableDataException {
        //init();
        PropertyDescriptor p = propertyDescriptors[i];
        return p.getDisplayName();
    }

    @Override
    public int getRowCount() throws TableDataException {
        init();
        return hisPatients.size();
    }

    @Override
    public Object getValueAt(int i, int j) {
        init();
        HisPatient hisPatient = hisPatients.get(i);

        PropertyDescriptor propertyDescriptor = propertyDescriptors[j];

        if (hisPatient == null) return  null;
        else
            return ReflectUtils.getProperty(hisPatient,propertyDescriptor);
    }

    public void init(){
        if (hisPatients != null) return;

        String patientID = null;

        ParameterProvider parameter = parameters[0];


        Object p = parameter.getValue();

        String name = parameter.getName();


        if (p!=null) patientID = p.toString();


        if (patientID!=null && patientID.length()>0) {

            QueryHisPatientReq hisPatientReq = new QueryHisPatientReq();

            hisPatientReq.getPatientIDs().add(patientID);

            hisPatients = new LinkedList<>();
            FRContext.getLogger().log(Level.INFO, "begin rpc");
            hisPatients.addAll(hisADTService.queryPatient(hisPatientReq));

            FRContext.getLogger().log(Level.INFO, "after rpc");
        }

    }
}
